layui.use(['table','form','element','layer','upload','laydate'], function(){
	var table = layui.table,
	form = layui.form,
	element = layui.element,
	layer = layui.layer,
	upload = layui.upload,
	laydate = layui.laydate,
	$ = layui.$;
	
	var currentPage =1;
	
	//初始化查询所有员工的方法
	loadUser("user/listByPramas");
	
	//日期
    laydate.render({
	   elem: '#birthday',
	   format: 'yyyy/MM/dd'
    });
	
	//刷新页面的方法
    function flushUser(currentPage){
	   table.reload('demo',{
		  page:{
			  curr:currentPage
		  }
	   });
    }
    //刷新的点击事件
    $("#flush").click(function(){
    	flushUser(currentPage);
    });
	
	//动态选项卡的监听(部门类型)
	element.on('tab(usertypeTab)', function(elem){
	   $("#userMeau").children("#unameLikeLi").remove();
	   if(elem.index>0){
		  var jsonUser = {};
		  jsonUser["usertype.utid"] = parseInt('10'+elem.index);
		  loadUser("user/listByPramas",jsonUser);
	   }else{
		   loadUser("user/listByPramas");
	   }
	});
	
	  //用户名模糊搜索
	  $("#btnlike").click(function(){
		 if($("#queryByuname").val()==""){
			 layer.msg("没有值。。。",{"icon":2,"time":2000});
		 }else{
			var jsonUser = {};
		 	jsonUser["uname"] = $("#queryByuname").val();
		 	if($("#unameLikeLi").val()=="007"){
		 		
		 	}else{
		 		$("#userMeau li").removeClass('layui-this'); 
		 		$("#userMeau").append('<li class="layui-this" id="unameLikeLi" value="007">模糊查询</li>');
		 	}
		 	loadUser("user/listByPramas",jsonUser);
		 }
	 	
	  });
	
	  //员工头像上传
	  upload.render({
		  elem:'#test1',
		  data:{path:'F:/实训 2018/作业/myshopImg/userHeader/'},
		  url:'user/uploadUserImg',
		  before:function(obj){  //上传之前回调
			  obj.preview(function(index,file,result){
				  $('#demo1').attr('src',result);
			  });
		  },
		  done:function(res){
			  var uploadIf = res.uploadImgIf.split(",");
			  if(uploadIf[0]=='success'){
				  layer.msg("图片上传成功",{"icon":6,"time":2000});
				  $("#userHeadImgInput").val(uploadIf[1]);
			  }else{
				  layer.msg("图片上传失败",{"icon":2,"time":2000});
			  }
		  },
		  error:function(){
			  layer.msg("图片上传异常",{"icon":3,"time":2000});
		  }
	  });
	
	//表格方法渲染(加载所有用户信息)
    function loadUser(url,jsonUser){
	  table.render({
	    elem: '#demo'
	    ,height: 515
	    ,width: 1800
	    ,url: url //数据接口
	    ,where:jsonUser
	    ,page: true //开启分页
	    ,limit:5 //每一页的数据条数
	    ,limits:[2,5,10,15,20,30]
	    ,cols: [[ //表头
	    	{type:'checkbox'}
	      ,{field: 'uid', title: 'ID', align:'center', width:120}
	      ,{field: 'uname', align:'center',title: '名称', width:120}
	      ,{field: 'avater', align:'center',title: '头像', width:120,templet:'<div><img src="/images/userHeader/{{d.avater}}"/></div>'}
	      ,{field: 'userName', align:'center',title: '用户名', width:120}
	      ,{field: 'pwd', align:'center',title: '密码', width:120,edit: 'test'}
	      ,{field: 'sex', align:'center',title: '性别', width:120,templet:'#Templetsex'}
	      ,{field: 'age', align:'center',title: '年纪', width:120}
	      ,{field: 'phone', align:'center',title: '手机', width:120}
	      ,{field: 'email', align:'center',title: '邮箱', width:165}
	      ,{field: 'hobby', align:'center',title: '爱好', width:120}
	      ,{field: 'birthday', align:'center',title: '生日', width:120}
	      ,{field: 'usertypename', align:'center',title: '用户类型', width:130}
	      ,{fixed: 'right',title:'操作', width:220, align:'center', toolbar: '#barDemo'}
	    ]],
	    done:function(res,curr,count){
	    	  currentPage = curr;
			  
		  	  hoverOpenImg();//显示大图
		  }
	  });
    }
    
    //放大头像
	function hoverOpenImg(){
	   var img_show = null; // tips提示
	   $('td img').hover(function(){
	       var img = "<img class='img_msg' src='"+$(this).attr('src')+"' style='width:230px;' />";
	       img_show = layer.tips(img, this,{
	       tips:[2, 'rgba(41,41,41,.5)']
	        ,area: ['260px']
	       });
	   },function(){
	       layer.close(img_show);
	   });
	   $('td img').attr('style','max-width:70px');
	}
	
	//监听单元格编辑
	table.on('edit(test)', function(obj){
	   //console.log(obj.value); //得到修改后的值
	   //console.log(obj.field); //当前编辑的字段名
	   //console.log(obj.data); //所在行的所有相关数据
	   var jsonUser = {};
	   jsonUser[obj.field] = obj.value;
	   jsonUser["uid"] = obj.data.uid;
	   UpdUser(jsonUser,obj.data.uname+",密码");
	});
	
	//监听性别操作
	form.on('switch(sexDemo)', function(obj){
	   var jsonUser = {};
	   var users = this.value.split(",");
	   jsonUser["uid"] = users[0];
	   if(obj.elem.checked){
	       jsonUser["sex"] = 1;
	   }else{
	       jsonUser["sex"] = 2;
	   }
	   UpdUser(jsonUser,users[1]+",性别");
	});
	  
	//监听工具条
	table.on('tool(test)', function(obj){
	   var data = obj.data;
	   if(obj.event === 'detail'){
	      layer.msg('ID：'+ data.uid + ' 的查看操作');
	   }else if(obj.event === 'del'){
	      layer.confirm('真的删除行么', function(index){
	    
  	       $.ajax({
	  	  		type:"post",
	  	  	    data:{"id":data.uid},
	  	  		url:"user/deleteById",
	  	  		success:function(res){
	  	  			if(res=="success"){
	  	  				layer.msg(data.uname+"，删除成功",{"icon":1,"time":2000});
	  	  			}else{
	  	  				layer.msg(data.uname+"，删除失败",{"icon":2,"time":2000});
	  	  			}
	  	  		},
	  	  		error:function(){
	  	  			layer.msg("服务器异常。",{"icon":3,"time":2000});
	  	  		}
	  	  	});
	    	//删除页面
	        obj.del();
	        layer.close(index);
	      });
	    }else if(obj.event === 'edit'){
	    	$('#demo1').attr('src','/images/userHeader/'+data.avater);
	    	$('#userHeadImgInput').val(data.avater);
		  	  layer.open({
		  		  type:1,
		  		  area:['500px','600px'],
		  		  title:'修改用户信息',
		  		  anim:4,
		  		  content:$("#updUserDiv"),
		  		  success:function(){
		  			  //弹框成功后的回调函数
		  			  $(':input','form')
		  			  	.not(':button,:submit,:reset,:hidden')
		  			  	.val('')
		  			  	.removeAttr('checked');
		  			
		  			  $('#uname').val(data.uname);
		  			  $('#userName').val(data.userName);
		  			  $("#pwd").val(data.pwd);
		  			  $('#age').val(data.age);
		  			  $('#email').val(data.email);
		  			  $('#birthday').val(data.birthday);
		  			  $("#avater").val(data.avater);
		  			  $('#hobby').val(data.hobby);
		  			  $('#phone').val(data.phone);
		  			  
		  			  if(data.sex==0){
		  				  $("#sexes").html('<input type="radio" name="sex" value="1" title="男"><input type="radio" name="sex" value="0" title="女" checked="">');
		  			  }else{
		  				  $("#sexes").html('<input type="radio" name="sex" value="1" title="男" checked=""><input type="radio" name="sex" value="0" title="女">');
		  			  }
		  			  form.render('radio');
		  			  
		  			  var hys = ["看书","跑步","足球","游泳","篮球","跳舞"];
			  		  var hy = data.hobby.split(",");  ["看书","跑步","足球"]  //3
	  	              var hobbys = ''; //html标签变量
	  	        	  $.each(hy, function(i) {  //3
	  	        		 $.each(hys,function(j){  //6  5   4
	  	        			if(hy[i] == hys[j]){
	  	        			   hys.splice($.inArray(hys[j],hys),1);  //把已匹配到的hys数组中的元素去掉
	  	        			   hobbys += '<input type="checkbox" name="hobby" title="'+hy[i]+'" value="'+hy[i]+'" checked="">';  //将匹配到的复选框改为默认选中
	  	        			   return false;
	  	        			};
	  	        		 });	
		  	  	      });
	  	        	  //hys["游泳","篮球","跳舞"]
	  	        	  $.each(hys,function(i){
	  	        		 hobbys += '<input type="checkbox" name="hobby" title="'+hys[i]+'" value="'+hys[i]+'">';	 //将未匹配到的复选框默认不选中
	  	        	  });
	  	        	  $("#hobbys").html(hobbys);
	  	        	  form.render('checkbox');
		  			  
		  			  $("#usertypedef").replaceWith('<option value="'+data.usertype.utid+','+data.usertype.utname+'" id="usertypedef" selected="selected">'+data.usertype.utname+'</option>');
		  			  form.render('select');
		  			  
			  		  //监听
		  			  form.on('submit(btn)', function(){
		  				  	var jsonUser = {};
		  				  	var params = '';
		  				    var usertypes = $("#usertype").val().split(",");
		  					var user = $("#updUserForm").serializeArray();
		  					$.each(user,function(){
		  						jsonUser[this.name] = this.value;
		  					});
		  					$("input:checkbox[name='hobby']:checked").each(function(){
		  						params += $(this).val() + ",";      //获取每一个选中的值
		  					});
		  					params = params.substring(0,params.length-1);
		  					jsonUser.hobby = params;
		  					jsonUser["uid"] = data.uid;
		  					jsonUser["usertype.utid"] = usertypes[0];
		  					//ajax修改
		  					UpdUser(jsonUser,data.uname);
			  			    obj.update({
			  			    	uname: jsonUser.uname,
			  			    	userName: jsonUser.userName,
			  			    	pwd: jsonUser.pwd,
			  			    	age: jsonUser.age,
			  			    	email: jsonUser.email,
			  			    	birthday: jsonUser.birthday,
			  			    	avater: jsonUser.avater,
			  			    	hobby: params,
			  			    	phone: jsonUser.phone,
			  			    	sex: jsonUser.sex,
			  			    	usertypename:usertypes[1]
			  				    //监听复选框
			  			    });
			  			    form.render('checkbox');
			  				layer.closeAll();
			  				return false;
			  		  });
		  		  }
		  	  });

	    }
	});
	
	//修改
	function UpdUser(jsonUser,msg){
		$.ajax({
			type:"post",
			url:"user/updT",
			data:jsonUser,
			success:function(data){
				if(data=="success"){
					layer.msg(msg+"修改成功。。。",{"icon":6,"time":2000});
				}else{
					layer.msg(msg+"修改失败！！！",{"icon":2,"time":2000});
				}
			},
			error:function(){
				layer.msg("对不起，服务器异常！！！",{"icon":3,"time":2000});
			}
		}); 
	  }
	
	//监听复选框
    table.on('checkbox(test)',function(obj){
	   //console.log(obj.checked);	//当前是否选中状态
	   //console.log(obj.data);	//选中行的相关数据
	   //console.log(obj.type);	//如果触发的是全选，则为all，单选为one
    });

	//批量删除
	$('#delManyUser').click(function(){ //获取选中数据
	    var checkStatus = table.checkStatus('demo')
	    ,data = checkStatus.data;
		if(data.length<1){
		    layer.alert('请选择数据')
		}else{
			layer.confirm("你确定要删除所选中的数据吗？？？",{icon: 7, title:'提示'},function(index){
				var params ="";
				for(var i=0;i<data.length;i++){
					params += data[i].uid+",";
				} 
				params = params.substring(0,params.length-1);
				delManyEmp("user/deletes",params);
				layer.close(index);
			});
		}
	   	//批量删除
	   	function delManyEmp(url,params){
		  $.ajax({
				type:"post",
				url:url,
				data:{params:params},
				success:function(data){
					if(data=="success"){
						layer.msg("批量删除数据成功。。",{"icon":6,"time":2000});
						flushUser(currentPage);
					}else{
						layer.msg("批量删除数据失败！！",{"icon":2,"time":2000});
					}
				},
				error:function(){
					layer.msg("对不起，服务器异常！！！",{"icon":3,"time":2000});
				}
			});
	   	 }
	  });
});